<script lang="jsx" setup>
import { inject, ref, watch } from 'vue';
import { Button, Modal, message } from 'ant-design-vue';
import { EditOutlined, DeleteOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { REQU, toFormData, useResp } from '@/net/requ.js';
import router from '@/router';

const auth = inject('auth');

const params = ref({
  start: 1,
  limit: 10,
  queryString: '',
  orderField: 'menu_name',
  orderType: 'DESC',
});

watch(params, getMenuList, { deep: true });

const columns = ref([
  {
    ellipsis: true,
    title: '菜单名称',
    dataIndex: 'menuName',
  },
  {
    title: '菜单 code',
    dataIndex: 'menuCode',
  },
  {
    title: '上级菜单 code',
    dataIndex: 'parentMenuCode',
    customRender: ({ text }) => text || '--',
  },
  {
    title: '菜单路由',
    dataIndex: 'routeKey',
  },
  {
    fixed: 'right',
    title: '操作',
    width: 230,
    customRender: ({ record }) => (
      <div class="op-btns icon">
        <Button
          type="link"
          onClick={() => useEditModal(record)}>
          {{
            icon: () => <EditOutlined />,
            default: () => '编辑'
          }}
        </Button>
        <Button
          type="link"
          style="color: rgb(200,0,0);"
          disabled={sending.value}
          onClick={() => (
            Modal.confirm({
              content: '确定删除此菜单？',
              cancelText: '取消',
              okText: '确定',
              onOk: () => delMenu(record.id.join(',')),
            })
          )}>
          {{
            icon: () => <DeleteOutlined />,
            default: () => '删除'
          }}
        </Button>
        <Button
          type="link"
          onClick={() => router.push({ path: '/func', query: { menuId: record.id } })}>
          {{
            icon: () => <UnorderedListOutlined />,
            default: () => '功能'
          }}
        </Button>
      </div>
    )
  },
]);

const dataSource = ref([]);
const total = ref(0);
const editModalProps = ref({ visible: false });

const formElem = ref();

const FormState = () => ({
  menuName: '',
  menuCode: '',
  parentMenuCode: '',
  routeKey: '',
  sort: 0,
});

const sending = ref(false);

const rules = {
  menuName: [ { required: true, message: '请输入菜单名称' } ],
  menuCode: [ { required: true, message: '请输入菜单 code' } ],
};

/** @type {import('vue').Ref<ReturnType<FormState>>} */
const formState = ref(null);

function useEditModal(row) {
  formState.value = Object.assign(FormState(), row);
  editModalProps.value.visible = true;
}

function onOk() {
  formElem.value
  .validate()
  .then(save)
  .then(() => {
    message.success('保存成功');
    editModalProps.value.visible = false;
    getMenuList();
  })
  .catch(() => {});
}

function getMenuList() {
  return REQU(`/api/menu/list?${ new URLSearchParams(params.value) }`)
  .then(useResp({
    succ: result => {
      dataSource.value = result.data.list;
      total.value = result.data.total;
      return result.data.list;
    }
  }));
}

function save() {
  sending.value = true;
  return REQU('/api/menu/save', {
    method: 'POST',
    body: toFormData(formState.value),
  })
  .then(useResp({
    succ: result => result,
  }))
  .finally(() => sending.value = false);
}

function delMenu(ids) {
  sending.value = true;
  return REQU('/api/menu/delete', {
    method: 'POST',
    body: toFormData({ ids })
  })
  .then(useResp({
    succ: result => {
      message.success('删除成功');
      getMenuList();
    },
  }))
  .finally(() => sending.value - false);
}

function main() {
  getMenuList();
}

main();
</script>

<template>
  <div class="simple">
    <a-button
      v-if="auth"
      type="primary"
      @click="() => useEditModal()">
      + 新建菜单
    </a-button>

    <a-table
      :columns="columns"
      :data-source="dataSource"
      :scroll="{ x: 1360 }"
      @change="pagination => params.start = pagination.current"
      :pagination="{
        current: params.start,
        pageSize: params.limit,
        total,
        pageSizeOptions: ['10', '20', '50'],
        showQuickJumper: true,
        showSizeChanger: true,
        position: ['bottomCenter'],
      }"
    >
    </a-table>

    <a-modal
      v-if="editModalProps.visible"
      v-model:visible="editModalProps.visible"
      :title="`${ formState.id ? '编辑' : '新建' }菜单`"
      @ok="onOk">
      <a-form
        ref="formElem"
        label-align="right"
        :label-col="{ span: 6 }"
        :model="formState"
        :rules="rules">
        <a-form-item required name="menuName" label="菜单名称">
          <a-input
            v-model:value="formState.menuName"
            :disabled="sending"
            allow-clear
            placeholder="请输入菜单名称">
          </a-input>
        </a-form-item>

        <a-form-item required name="menuCode" label="菜单 code">
          <a-input
            v-model:value="formState.menuCode"
            :disabled="sending"
            allow-clear
            placeholder="请输入菜单 code">
          </a-input>
        </a-form-item>

        <a-form-item name="parentMenuCode" label="上级菜单 code">
          <a-input
            v-model:value="formState.parentMenuCode"
            :disabled="sending"
            allow-clear
            placeholder="请输入上级菜单 code">
          </a-input>
        </a-form-item>

        <a-form-item name="routeKey" label="菜单路由">
          <a-input
            v-model:value="formState.routeKey"
            :disabled="sending"
            allow-clear
            placeholder="请输入菜单路由">
          </a-input>
        </a-form-item>

        <a-form-item name="sort" label="顺序">
          <a-input-number
            v-model:value="formState.sort"
            :min="0"
            :step="1"
            :disabled="sending"
            placeholder="请输入顺序">
          </a-input-number>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>
